//
//  QRCodeViewController.swift
//  swiftWeibo
//
//  Created by WangQiang on 2016/10/31.
//  Copyright © 2016年 WangQiang. All rights reserved.
//

import UIKit
import AVFoundation

class QRCodeViewController: UIViewController {
    @IBAction func leftBtnClick(_ sender: AnyObject) {
        dismiss(animated: true, completion: nil)
    }
    @IBAction func rightBtnClick(_ sender: AnyObject) {
        
    }
    @IBOutlet weak var scanLine_top: NSLayoutConstraint!
    @IBOutlet var containerView: UIView!
    @IBOutlet weak var containerViewHeight: NSLayoutConstraint!
    @IBOutlet weak var coustomLabel: UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        scanQRCode()
    }
    

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        startAnimation()
    }
    
    private func scanQRCode(){
        //1.判断输入是否能够加入到会话中
        if !session.canAddInput(input){
            return
        }
        //2.判断输出是否能够加入到会话中
        if !session.canAddOutput(output){
            return
        }
        
        //3.输入输出添加到会话中
        session.addInput(input)
        session.addOutput(output)
        
        //4.设置输出能够解析的数据类型
        //注意点:设置数据类型一定要在输出对象添加到会话之后才能设置
        output.metadataObjectTypes = output.availableMetadataObjectTypes
        //5.设置监听输出解析到的数据
        output.setMetadataObjectsDelegate(self, queue:DispatchQueue.main)
     

        //6.添加预览图层
//        previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
        previewLayer.frame = view.bounds
        view.layer.insertSublayer(previewLayer, at: 0)
        
        // 7.添加容器图层
        view.layer.addSublayer(containerLayer)
        containerLayer.frame = view.bounds
        
        
        //8.开始扫描
        session.startRunning()
    }
//    MARK:动画
    fileprivate func startAnimation(){
        scanLine_top.constant = -containerViewHeight.constant
        
        view.layoutIfNeeded()
        UIView.animate(withDuration: 1.0) {
            UIView.setAnimationRepeatCount(MAXFLOAT)
            self.scanLine_top.constant = self.containerViewHeight.constant*0.5
            self.view.layoutIfNeeded()
        }
    }
    
    private lazy var  input:AVCaptureDeviceInput! = {
        let device = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
           return try! AVCaptureDeviceInput.init(device: device)
    }()
    private lazy var session = AVCaptureSession()
    
    private lazy var output:AVCaptureMetadataOutput = {
        let out = AVCaptureMetadataOutput.init()
        let viewRect = self.view.frame
        let containerRect = self.containerView.frame
        
        let x = containerRect.origin.y / viewRect.height;
        let y = containerRect.origin.x / viewRect.width;
        let width = containerRect.height / viewRect.height;
        let height = containerRect.width / viewRect.width;
        // 3.设置输出对象解析数据时感兴趣的范围 (按照比例来)
//        out.rectOfInterest = CGRect(x: x, y: y, width: width, height: height)
        return out
        
    }()
    fileprivate lazy var previewLayer:AVCaptureVideoPreviewLayer = AVCaptureVideoPreviewLayer.init(session: self.session)
    /// 专门用于保存描边的图层
    fileprivate lazy var containerLayer: CALayer = CALayer()

}
extension QRCodeViewController:AVCaptureMetadataOutputObjectsDelegate{
    
    func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, from connection: AVCaptureConnection!) {
        //AVMetadataMachineReadableCodeObject
        coustomLabel.text = (metadataObjects.last as AnyObject).stringValue
        // 2.拿到扫描到的数据
        guard let metadata = metadataObjects.last as? AVMetadataObject else
        {
            return
        }
        // 通过预览图层将corners值转换为我们能识别的类型
        let objc = previewLayer.transformedMetadataObject(for: metadata)
        // 2.对扫描到的二维码进行描边
        drawLines(objc as! AVMetadataMachineReadableCodeObject)
    }
    private func drawLines(_ objc:AVMetadataMachineReadableCodeObject){
        
        guard let corners = objc.corners as [AnyObject]!  else {
            
            return
        }
        let layer = CAShapeLayer()
        layer.lineWidth = 2
        layer.strokeColor = UIColor.green.cgColor
        layer.fillColor = UIColor.clear.cgColor
        
        let path = UIBezierPath()
        var point = CGPoint.zero
        var index = 0
        
        
        
        point = CGPoint.init(dictionaryRepresentation: corners[index] as! CFDictionary)!
        path.move(to: point)
             index += 1
        while index < corners.count {
         path.addLine(to: CGPoint.init(dictionaryRepresentation: corners[index] as! CFDictionary)!)
            index += 1
        }
        path.close()
        layer.path = path.cgPath
        
        containerLayer.addSublayer(layer)
    }
    
}

extension QRCodeViewController:UITabBarDelegate{
    func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
        if(item.tag == 1){
            containerViewHeight.constant = 100;
        }else{
            containerViewHeight.constant = 200;
        }
        startAnimation()
    }
    
}
